//Import utils for some common data handle.
import {utils} from '../../../utils/utils';

const dimension2ArticleListService = {
  //Define the specified condition query parameters.
  articleListWithCondQueryRequest : {
    originCollection : "Article",
    fromCollectionsLookUpParmas : [
                              {
                                name : "User",
                                let : {
                                  userID : '$userID'
                                },
                                pipeline : [
                                  {
                                    operator : 'eq',
                                    fieldName : '$userID',
                                    definedName : '$$userID'
                                  },                                 
                                ],
                                project : {
                                  _id: 0,
                                  nickName: 1,
                                },
                                as : 'Article2User',
                              }
                            ],
    orderBy : 'createdTime',
    limit : 18
  },

  resolveAggregatedArticleList(articleList, obj) {
    utils.mockUpArticlePic(obj);

    //Handle Created Time from Number to Date in MP side, because there may be the other Date transfer scenario in different part. 
    return utils.transferLongToDate(articleList);
  },

  /*
    Store the resource file by the target Cloud File ID. 
    Now is support for Pic file.  
  */
  storeArticleICONIntoLocalStorage(articleList) {
    console.log(`The target articleList.length ========= ${articleList.length}`);

    const fileSystemManager = wx.getFileSystemManager();
    const USER_DATA_PATH = wx.env.USER_DATA_PATH;

    articleList.forEach(onePageList => {
      let dataList = onePageList.list;

      if(dataList) {
        dataList.forEach(article => {
          try{
            let articleICONFileID = article.iconID;
            wx.cloud.downloadFile({
              fileID: articleICONFileID,
            })
            .then(res => {
                // get temp file URL
                let tempFilePath = res.tempFilePath;
                console.log(`Succeed to get the target pic file tempFilePath : ${tempFilePath} !!`);
    
                let articleID = article.articleID;
    
                if(tempFilePath) {  
                  let picStoredPath = USER_DATA_PATH + `/${articleID}.jpg`;
                  let savedFilePath = fileSystemManager.saveFileSync(tempFilePath, picStoredPath);
                  
                  wx.setStorageSync(articleICONFileID, savedFilePath);
                  console.log(`Succeed to save the pic : '${picStoredPath}' into savedFilePath : '${savedFilePath}', then save into the Local Storage as the key '${articleICONFileID}' for article '${articleID}' !!`);
                }
    
                console.log(`Finish to handle the article '${articleID}' of the relevant 'articleICONFileIDObj' for saving the 'saveFilePath' into Local Storage !!`);
            })
            .catch(error => {
              console.log(`When downloading the pic file '${articleICONFileID}', there is exception : ${error} !!`);
            });
          }catch(e) {
            console.log(`When handling the pic files download & save into '${USER_DATA_PATH}', there is exception : ${e} !!`);
          }
        });
      }
    });
  },

  /* 
    Save the pic file into local File System.
    Save the savedFilePath into Local Storage, then could retrieve the resource from Local Storage instead of Clould Base at all.
  */
  async reloadResourceInLocalStorage(articleList) {
    try {
      /*
        Retrieve the keys in Local Stoarge in order to decide which place should the pic files to being loaded.
      */
      let localStorageInfo = wx.getStorageInfoSync();
      let localStorageInfoKeysSize = localStorageInfo.keys.length;
      console.log(`The 'localStorageInfo.keys.length' : ${localStorageInfoKeysSize}, localStorageInfo.currentSize ========== ${localStorageInfo.currentSize}, localStorageInfo.limitSize =========== ${localStorageInfo.limitSize} !!`);

      /*
        Try to reload the pic resource from Local Storage
      */
      let reloadPicCount = 0;
      let articleListSize = 0;

      //At least contains 18 pieces of Pic file.
      if(localStorageInfoKeysSize >= 10) {
        articleList.forEach(onePageList => {
          let dataList = onePageList.list;
          articleListSize += dataList.length; 

          if(dataList) {
            dataList.forEach(article => {
              let articleIconID = article.iconID;
              let articleID = article.articleID;
              let articleICONLocalFilePath = wx.getStorageSync(articleIconID);
              console.log(`Retrieve the target pic file local storage path : '${articleICONLocalFilePath}' of the key : '${articleIconID}' !!`);

              if(articleICONLocalFilePath) {
                article.iconID = articleICONLocalFilePath;

                reloadPicCount++;

                console.log(`Succeed to reload the pic file : '${articleICONLocalFilePath}' as the key : '${articleIconID}' stored in Local Storage, for the article : '${articleID}' : '${article.title}', reloadPicCount : ${reloadPicCount} !!`);
              }
            });
          }
        }
      )}

      /*
        If there is missing Pic resource in Local Storage,
        request the resource from Cloud Base.
      */
      console.log(`Compare the 'articleListSize' & 'reloadPicCount' : articleListSize : ${articleListSize}, reloadPicCount : ${reloadPicCount} !!`);
      
      //The whole article list size is 18, which is the "Dimension To Article" part. 
      if(reloadPicCount != articleListSize) {
        console.log(`Didn't retrieve all the pic file in Local File System, ready to store the target article pics into Local File System & Storage!!`);
        this.storeArticleICONIntoLocalStorage(articleList);
      }

      return await articleList;
    } catch (e) {
      console.log(`When handle the Pic resource for each article of article list, there is exception : ${e}`);
    }
  },

  async aggregatedArticleList (obj, mockArticleList, loadFromCloudBase) {
    if(loadFromCloudBase) {
      return wx.cloud.callFunction({
        name : "AggregatedLookUpForDimension2ArticleList",
        data : {
          queryRequest : this.articleListWithCondQueryRequest
        }
      })
      .then(res => {
        let articleList = res.result;

        //Reload the pic from local storage.
        this.reloadResourceInLocalStorage(articleList);

        return this.resolveAggregatedArticleList(articleList, obj);
      });
    }
    else{
      return this.resolveAggregatedArticleList(mockArticleList, obj);
    }
  },
}
export {dimension2ArticleListService};